package com.xb.system.service.impl;

import com.google.common.hash.BloomFilter;
import com.xb.system.redis.UserPhoneBloomFilterConfig;
import com.xb.system.service.FileHandler;
import com.xb.model.domain.Users;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;



@Component
@Slf4j
public class WordDocumentHandler implements FileHandler {

    @Value("${file.batch.size}")
    private int batchSize;

    @Value("${file.thread.pool.size}")
    private int threadPoolSize;

    @Autowired
    private DynamicDataSplitterServiceImpl dynamicDataSplitterService;
    
    @Resource
    private UserPhoneBloomFilterConfig userPhoneBloomFilterConfig;

    @Override
    public void handleFile(String file) throws IOException {
        BloomFilter<String> bloomFilter = userPhoneBloomFilterConfig.createBloomFilter();
        try (InputStream is = Files.newInputStream(Paths.get(file));
             XWPFDocument document = new XWPFDocument(is)) {

            List<XWPFParagraph> paragraphs = document.getParagraphs();
            List<String> lines = paragraphs.stream()
                    .map(XWPFParagraph::getText)
                    .collect(Collectors.toList());

            ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);

            List<Users> batch = new ArrayList<>();

            // 提交每一行数据的处理任务到线程池
            for (String line : lines) {
                executor.submit(() -> {
                    batch.addAll(dynamicDataSplitterService.processLine(line,bloomFilter));

                    if (batch.size() >= batchSize) {
                        dynamicDataSplitterService.saveBatch(batch);
                        batch.clear();
                    }
                });
            }

            executor.shutdown();
            try {
                executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                log.error("线程池在等待任务完成时被中断：{}", e.getMessage());
                Thread.currentThread().interrupt();
            }

            // 处理剩余的数据
            if (!batch.isEmpty()) {
                dynamicDataSplitterService.saveBatch(batch);
            }

        } catch (IOException e) {
            log.error("处理 Word 文档时发生错误: {}", e.getMessage());
            throw e;
        }
    }

/*    @Override
    public void handleFile(MultipartFile file) throws IOException {
        try (InputStream is = file.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {

            ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);

            List<String> lines = reader.lines().collect(Collectors.toList());
            int chunkSize = (int) Math.ceil((double) lines.size() / threadPoolSize);

            for (int i = 0; i < threadPoolSize; i++) {
                int fromIndex = i * chunkSize;
                int toIndex = Math.min(fromIndex + chunkSize, lines.size());

                List<String> subList = lines.subList(fromIndex, toIndex);

                executor.submit(() -> processHtmlLines(subList));
            }

            executor.shutdown();
            try {
                executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                log.error("线程池在等待任务完成时被中断：{}", e.getMessage());
                Thread.currentThread().interrupt();
            }

        } catch (IOException e) {
            log.error("处理 HTML 文档时发生错误: {}", e.getMessage());
            throw e;
        }
    }

    private void processHtmlLines(List<String> lines) {
        List<Users> batch = new ArrayList<>();

        for (String line : lines) {
            String[] parts = line.split("\\s+");
            if (parts.length < 2 || !parts[phoneIndex].matches("^1[3456789]\\d{9}$")) {
                continue;
            }

            String phone = parts[phoneIndex];
            String name = parts.length >= (nameIndex + 1) ? StrUtil.hide(parts[nameIndex], 1, parts[nameIndex].length()) : parts[nameIndex];

            batch.add(new Users(null, phone, name));

            for (int index : extraPhoneIndexes) {
                if (index >= parts.length) {
                    continue;
                }
                String extraPhone = parts[index].trim();
                if (extraPhone.matches("^1[3456789]\\d{9}$")) {
                    batch.add(new Users(null, extraPhone, name));
                }
            }

            if (batch.size() >= batchSize) {
                saveBatch(batch);
                batch.clear();
            }
        }

        if (!batch.isEmpty()) {
            saveBatch(batch);
        }
    }

    private void saveBatch(List<Users> batch) {
        // 实现保存批处理逻辑，使用了动态数据分片器中的方法
        MyDynamicDataSplitterServiceImpl splitterService = new MyDynamicDataSplitterServiceImpl();
        splitterService.saveBatch(batch);
        log.info("已保存 {} 条数据到数据库。", batch.size());
    }*/
}
